﻿'
' DKP for DotNetNuke® - http://dkpdnn.codeplex.com
' Copyright (c) 2008
' by Casey Lengacher ( http://dkpdnn.codeplex.com )
'
' DotNetNuke®, DNN®, and the DotNetNuke logo are trademarks of DotNetNuke Corporation.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
'

Imports System.Net
Imports DotNetNuke.Common.Utilities

Namespace DotNetNuke.Modules.tss_DKP

    Partial Public Class tss_ucInstances

        Inherits Entities.Modules.PortalModuleBase

#Region "Private Variables"

        Private Enum PageState As Integer
            NotSet = -1
            View = 0
            Add = 1
            SingleUpdate = 2
            MultiUpdate = 3
        End Enum

#End Region

#Region "Private Properties"

        Private Property vsPageSize() As Integer
            Get
                If ViewState("tss_InstancePageSize") Is Nothing Then
                    If (Request.Cookies.Get("tss_InstancePageSize") Is Nothing) Then
                        Return ddlPageSize.Items(0).Value
                    Else
                        Return CInt(Request.Cookies.Get("tss_InstancePageSize").Value)
                    End If
                Else
                    Return CInt(ViewState("tss_InstancePageSize"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_InstancePageSize") = Value
                Response.Cookies("tss_InstancePageSize").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_InstancePageSize").Value = Value
            End Set
        End Property

        Private Property vsSortExpression() As String
            Get
                If ViewState("tss_InstanceSortExpression") Is Nothing Then
                    If (Request.Cookies.Get("tss_InstanceSortExpression") Is Nothing) Then
                        Return "InstanceName"
                    Else
                        Return CStr(Request.Cookies.Get("tss_InstanceSortExpression").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_InstanceSortExpression"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_InstanceSortExpression") = Value
                Response.Cookies("tss_InstanceSortExpression").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_InstanceSortExpression").Value = Value
            End Set
        End Property

        Private Property vsSortDirection() As String
            Get
                If ViewState("tss_InstanceSortDirection") Is Nothing Then
                    If (Request.Cookies.Get("tss_InstanceSortDirection") Is Nothing) Then
                        Return "ASC"
                    Else
                        Return CStr(Request.Cookies.Get("tss_InstanceSortDirection").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_InstanceSortDirection"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_InstanceSortDirection") = Value
                Response.Cookies("tss_InstanceSortDirection").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_InstanceSortDirection").Value = Value
            End Set
        End Property

        Private Property vsCurrentPage() As Integer
            Get
                If ViewState("tss_InstanceCurrentPage") Is Nothing Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_InstanceCurrentPage"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_InstanceCurrentPage") = Value
            End Set
        End Property

        Private Property vsTotalPages() As Integer
            Get
                If ViewState("tss_InstanceTotalPages") Is Nothing Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_InstanceTotalPages"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_InstanceTotalPages") = Value
            End Set
        End Property

        Private Property vsPageState() As PageState
            Get
                If ViewState("tss_InstancePageState") Is Nothing Then
                    Return PageState.NotSet
                Else
                    Return CStr(ViewState("tss_InstancePageState"))
                End If
            End Get
            Set(ByVal Value As PageState)
                ViewState("tss_InstancePageState") = Value
            End Set
        End Property

#End Region

#Region "Private Methods"

        Private Sub BindPage()

            Dim tss_DKP As New tss_DataController
            Dim intRowsAffected As Integer
            Dim intPageNumber As Integer = vsCurrentPage
            Dim dblPagesAffected As Double = 1

            ddlPageSize.SelectedValue = ddlPageSize.Items.FindByText(vsPageSize).Value

            grdInstances.PageSize = vsPageSize

            For Each currentColumn As DataGridColumn In grdInstances.Columns
                currentColumn.HeaderText = currentColumn.HeaderText.Substring(0, _
                    IIf(currentColumn.HeaderText.IndexOf(" <img") > 0, currentColumn.HeaderText.IndexOf(" <img"), currentColumn.HeaderText.Length))
                If (currentColumn.SortExpression = vsSortExpression) Then
                    If (vsSortDirection = "ASC") Then
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_uparrow.png' border=0 height=10 width=10>"
                    Else
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_downarrow.png' border=0 height=10 width=10>"
                    End If
                End If
            Next

            grdInstances.DataSource = tss_DKP.tss_GetInstancesByPage(CInt(Settings("BoardID")), intPageNumber, grdInstances.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
            grdInstances.DataBind()

            If (grdInstances.Items.Count = 0) And (intPageNumber > 1) Then
                intPageNumber = intPageNumber - 1
                vsCurrentPage = intPageNumber.ToString()
                grdInstances.DataSource = tss_DKP.tss_GetInstancesByPage(CInt(Settings("BoardID")), intPageNumber, grdInstances.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
                grdInstances.DataBind()
            End If

            dblPagesAffected = System.Math.Ceiling(intRowsAffected / grdInstances.PageSize)
            If (dblPagesAffected < 1) Then
                dblPagesAffected = 1
            End If
            vsTotalPages = dblPagesAffected.ToString()
            lblCurrentPage.Text = vsCurrentPage
            lblTotalPages.Text = vsTotalPages

            If (intPageNumber = 1) Then
                lnkPreviousPage.Enabled = False

                If (dblPagesAffected > 1) Then
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                Else
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                End If
            Else
                lnkPreviousPage.Enabled = True

                If (intPageNumber = dblPagesAffected) Then
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                Else
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                End If
            End If

            If (DotNetNuke.Security.PortalSecurity.IsInRoles(Me.ModuleConfiguration.AuthorizedEditRoles)) And Not (UserId = -1) Then
                pnlEditPanel.Visible = True
                grdInstances.Columns(0).Visible = True
            Else
                pnlEditPanel.Visible = False
                grdInstances.Columns(0).Visible = False
            End If

        End Sub

        Private Sub ManagePageState(ByVal PageState As PageState)

            vsPageState = PageState

            If (PageState = PageState.View) Then
                grdInstances.Enabled = True
                BindPage()
            Else
                grdInstances.Enabled = False
            End If

            If (PageState = PageState.View) Then
                pnlEditPanelForm.Visible = False
            Else
                pnlEditPanelForm.Visible = True
            End If

            txtInstanceName.Text = Null.NullString
            txtInstanceWowHeadID.Text = Null.NullString
            chkInstanceHeroicFlag.Checked = False

            lblWarning.Text = Null.NullString

            If (PageState = PageState.Add) Or (PageState = PageState.SingleUpdate) Then

                pnlInstanceName.Visible = True
                pnlInstanceWowHeadID.Visible = True

                txtInstanceName.Focus()

            ElseIf (PageState = PageState.MultiUpdate) Then

                pnlInstanceName.Visible = False
                pnlInstanceWowHeadID.Visible = False

                chkInstanceHeroicFlag.Focus()

            End If

        End Sub

        Private Function SyncInstance(ByVal intInstanceID As Integer) As String

            Dim rgxMobMatchCollectionsL0, rgxMobMatchCollectionsL1 As MatchCollection

            Dim strMobRegexPatterns(1) As String
            strMobRegexPatterns(0) = "^new Listview\(\{template: 'npc', id: 'bosses', [a-zA-Z0-9:.,'_\\\[\]\{\}\- ]*\);"
            strMobRegexPatterns(1) = "id:([0-9]*),name:'([a-zA-Z0-9\\' ]*)'"

            Dim rgxItemMatchCollectionsL0, rgxItemMatchCollectionsL1 As MatchCollection

            Dim strItemNormalRegexPatterns(1) As String
            strItemNormalRegexPatterns(0) = "^new Listview\(\{template: 'item', id: 'normal-drops', [a-zA-Z0-9:.,'_\\\[\]\{\}\-\(\) ]*\);"
            strItemNormalRegexPatterns(1) = "id:([0-9]*),name:'([a-zA-Z0-9\\' ]*)'"

            Dim strItemHeroicRegexPatterns(1) As String
            strItemHeroicRegexPatterns(0) = "^new Listview\(\{template: 'item', id: 'heroic-drops', [a-zA-Z0-9:.,'_\\\[\]\{\}\-\(\) ]*\);"
            strItemHeroicRegexPatterns(1) = "id:([0-9]*),name:'([a-zA-Z0-9\\' ]*)'"

            Dim objWebClient As New WebClient()

            Dim strInstanceURL As String
            Dim objInstanceUTF8 As New UTF8Encoding()

            Dim strMobURL As String
            Dim objMobUTF8 As New UTF8Encoding()

            Dim tss_DKP As New tss_DataController
            Dim objInstance As tss_InstanceInfo
            Dim objMob As New tss_MobInfo
            Dim objItem As New tss_ItemInfo
            Dim objDrop As New tss_DropInfo
            Dim objExistingMob As tss_MobInfo
            Dim objExistingItem As tss_ItemInfo

            objMob = CBO.InitializeObject(objMob, GetType(tss_MobInfo))
            objItem = CBO.InitializeObject(objItem, GetType(tss_ItemInfo))
            objDrop = CBO.InitializeObject(objDrop, GetType(tss_DropInfo))

            objInstance = tss_DKP.tss_GetInstance(intInstanceID)

            If Not (objInstance Is Nothing) Then

                If (objInstance.InstanceWowHeadID = "") Then
                    Return Null.NullString
                End If

                strInstanceURL = "http://www.wowhead.com/?zone=" + objInstance.InstanceWowHeadID

                rgxMobMatchCollectionsL0 = Regex.Matches(objInstanceUTF8.GetString(objWebClient.DownloadData(strInstanceURL)), _
                                                          strMobRegexPatterns(0), RegexOptions.Multiline)

                For Each rgxMobMatchL0 In rgxMobMatchCollectionsL0

                    rgxMobMatchCollectionsL1 = Regex.Matches(rgxMobMatchL0.Value, strMobRegexPatterns(1))

                    For Each rgxMobMatchL1 In rgxMobMatchCollectionsL1

                        objExistingMob = tss_DKP.tss_GetMobByName(rgxMobMatchL1.Groups.Item(2).Value.Replace("\", ""), intInstanceID)

                        If (objExistingMob Is Nothing) Then

                            objMob.MobName = rgxMobMatchL1.Groups.Item(2).Value.Replace("\", "")
                            objMob.MobValue = "0"
                            objMob.MobWowHeadID = rgxMobMatchL1.Groups.Item(1).Value
                            objMob.MobHeroicFlag = False
                            objMob.MobAttendanceFlag = True
                            objMob.InstanceID = objInstance.InstanceID

                            Try
                                objMob.MobID = tss_DKP.tss_AddMob(objMob)
                            Catch ex As ApplicationException
                            End Try

                        Else

                            objMob = objExistingMob

                        End If

                        strMobURL = "http://www.wowhead.com/?npc=" + rgxMobMatchL1.Groups.Item(1).Value

                        rgxItemMatchCollectionsL0 = Regex.Matches(objMobUTF8.GetString(objWebClient.DownloadData(strMobURL)), _
                                      strItemNormalRegexPatterns(0), RegexOptions.Multiline)

                        For Each rgxItemMatchL0 In rgxItemMatchCollectionsL0

                            rgxItemMatchCollectionsL1 = Regex.Matches(rgxItemMatchL0.Value, strItemNormalRegexPatterns(1))

                            For Each rgxItemMatchL1 In rgxItemMatchCollectionsL1

                                objExistingItem = tss_DKP.tss_GetItemByName(rgxItemMatchL1.Groups.Item(2).Value.Replace("\", "").Remove(0, 1), CInt(Settings("BoardID")))

                                If (objExistingItem Is Nothing) Then

                                    objItem.ItemName = rgxItemMatchL1.Groups.Item(2).Value.Replace("\", "").Remove(0, 1)
                                    objItem.ItemValue = "0"
                                    objItem.ItemWowHeadID = rgxItemMatchL1.Groups.Item(1).Value
                                    objItem.BoardID = CInt(Settings("BoardID"))

                                    Try
                                        objItem.ItemID = tss_DKP.tss_AddItem(objItem)
                                    Catch ex As ApplicationException
                                    End Try

                                Else

                                    objItem = objExistingItem

                                End If

                                objDrop.MobID = objMob.MobID
                                objDrop.ItemID = objItem.ItemID

                                Try
                                    tss_DKP.tss_AddDrop(objDrop)
                                Catch ex As ApplicationException
                                End Try

                            Next
                        Next

                        If (objInstance.InstanceHeroicFlag) Then

                            objExistingMob = tss_DKP.tss_GetMobByName(rgxMobMatchL1.Groups.Item(2).Value.Replace("\", "") + " (Heroic)", intInstanceID)

                            If (objExistingMob Is Nothing) Then

                                objMob.MobName = rgxMobMatchL1.Groups.Item(2).Value.Replace("\", "") + " (Heroic)"
                                objMob.MobValue = "0"
                                objMob.MobWowHeadID = rgxMobMatchL1.Groups.Item(1).Value
                                objMob.MobHeroicFlag = True
                                objMob.MobAttendanceFlag = True
                                objMob.InstanceID = objInstance.InstanceID

                                Try
                                    objMob.MobID = tss_DKP.tss_AddMob(objMob)
                                Catch ex As ApplicationException
                                End Try

                            Else

                                objMob = objExistingMob

                            End If

                            rgxItemMatchCollectionsL0 = Regex.Matches(objMobUTF8.GetString(objWebClient.DownloadData(strMobURL)), _
                                                                            strItemHeroicRegexPatterns(0), RegexOptions.Multiline)

                            For Each rgxItemMatchL0 In rgxItemMatchCollectionsL0

                                rgxItemMatchCollectionsL1 = Regex.Matches(rgxItemMatchL0.Value, strItemNormalRegexPatterns(1))

                                For Each rgxItemMatchL1 In rgxItemMatchCollectionsL1

                                    objExistingItem = tss_DKP.tss_GetItemByName(rgxItemMatchL1.Groups.Item(2).Value.Replace("\", "").Remove(0, 1), CInt(Settings("BoardID")))

                                    If (objExistingItem Is Nothing) Then

                                        objItem.ItemName = rgxItemMatchL1.Groups.Item(2).Value.Replace("\", "").Remove(0, 1)
                                        objItem.ItemValue = "0"
                                        objItem.ItemWowHeadID = rgxItemMatchL1.Groups.Item(1).Value
                                        objItem.BoardID = CInt(Settings("BoardID"))

                                        Try
                                            objItem.ItemID = tss_DKP.tss_AddItem(objItem)
                                        Catch ex As ApplicationException
                                        End Try

                                    Else

                                        objItem = objExistingItem

                                    End If

                                    objDrop.MobID = objMob.MobID
                                    objDrop.ItemID = objItem.ItemID

                                    Try
                                        tss_DKP.tss_AddDrop(objDrop)
                                    Catch ex As ApplicationException
                                    End Try

                                Next
                            Next

                        End If

                    Next
                Next

            End If

            Return Null.NullString

        End Function

#End Region

#Region "Private Event Handlers"

        Private Sub ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdInstances.ItemDataBound

            If (e.Item.ItemType.Equals(ListItemType.Item)) Or (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                Dim lblInstanceID As Label = e.Item.FindControl("lblInstanceID")
                Dim lnkInstanceWowHeadID As HyperLink = e.Item.FindControl("lnkInstanceWowHeadID")
                Dim lblInstanceName As Label = e.Item.FindControl("lblInstanceName")
                Dim imgInstanceHeroicFlag As Image = e.Item.FindControl("imgInstanceHeroicFlag")

                Dim objInstance As tss_InstanceInfo = e.Item.DataItem

                lblInstanceID.Text = objInstance.InstanceID.ToString()
                lblInstanceID.Visible = False

                If (objInstance.InstanceWowHeadID.Length = 0) Then
                    lnkInstanceWowHeadID.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_blank.png"
                    lnkInstanceWowHeadID.Enabled = False
                Else
                    lnkInstanceWowHeadID.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_wowhead.png"
                    lnkInstanceWowHeadID.NavigateUrl = "http://www.wowhead.com/?zone=" + objInstance.InstanceWowHeadID
                    lnkInstanceWowHeadID.Target = "_new"
                    lnkInstanceWowHeadID.Enabled = True
                    lnkInstanceWowHeadID.ToolTip = "View WowHead"
                End If

                lblInstanceName.Text = objInstance.InstanceName

                If (objInstance.InstanceHeroicFlag) Then
                    imgInstanceHeroicFlag.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_checked.png"
                Else
                    imgInstanceHeroicFlag.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_blank.png"
                End If

            End If

        End Sub

        Private Sub ItemCreated(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdInstances.ItemCreated

            If (e.Item.ItemType.Equals(ListItemType.Header)) Then

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridHeader" + grdInstances.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Item)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridItem" + grdInstances.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridAltItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridAltItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridAltItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridAltItem" + grdInstances.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Footer)) Then

                e.Item.Visible = False

            End If

        End Sub

        Private Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlPageSize.SelectedIndexChanged

            If (sender.Equals(ddlPageSize)) Then

                vsPageSize = ddlPageSize.SelectedValue
                ManagePageState(PageState.View)

            End If

        End Sub

        Private Sub SortCommand(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs) Handles grdInstances.SortCommand

            If (vsSortExpression = e.SortExpression) Then
                If (vsSortDirection = "ASC") Then
                    vsSortDirection = "DESC"
                ElseIf (vsSortDirection = "DESC") Then
                    vsSortDirection = "ASC"
                End If
            Else
                vsSortExpression = e.SortExpression
                vsSortDirection = "ASC"
            End If

            ManagePageState(PageState.View)

        End Sub

        Private Sub Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkFirstPage.Click, lnkPreviousPage.Click, _
            lnkNextPage.Click, lnkLastPage.Click, lnkAdd.Click, lnkUpdate.Click, lnkDelete.Click, lnkSync.Click, lnkSubmit.Click, lnkCancel.Click

            Dim tss_DKP As New tss_DataController

            lblWarning.Text = Null.NullString

            If (sender.Equals(lnkFirstPage)) Then

                vsCurrentPage = 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkPreviousPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) - 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkNextPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) + 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkLastPage)) Then

                vsCurrentPage = vsTotalPages
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkAdd)) Then

                ManagePageState(PageState.Add)

            ElseIf (sender.Equals(lnkUpdate)) Then

                Dim boolIsChecked As Boolean = False

                For Each currentInstance As DataGridItem In grdInstances.Items

                    If (currentInstance.ItemType.Equals(ListItemType.Item)) Or (currentInstance.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkInstance As CheckBox = currentInstance.FindControl("chkInstance")
                        Dim lblInstanceID As Label = currentInstance.FindControl("lblInstanceID")

                        If (chkInstance.Checked) And (boolIsChecked) Then

                            ManagePageState(PageState.MultiUpdate)
                            Exit For

                        ElseIf (chkInstance.Checked) And Not (boolIsChecked) Then

                            boolIsChecked = True

                            ManagePageState(PageState.SingleUpdate)

                            Dim objExistingInstance As tss_InstanceInfo = tss_DKP.tss_GetInstance(CInt(lblInstanceID.Text))

                            If (objExistingInstance Is Nothing) Then
                                ManagePageState(PageState.View)
                                lblWarning.Text = "Error: Instance in selection not found."
                                Exit For
                            Else
                                txtInstanceName.Text = objExistingInstance.InstanceName
                                txtInstanceWowHeadID.Text = objExistingInstance.InstanceWowHeadID
                                chkInstanceHeroicFlag.Checked = objExistingInstance.InstanceHeroicFlag
                            End If

                        End If

                    End If

                Next

                If Not (boolIsChecked) Then
                    ManagePageState(PageState.View)
                End If

            ElseIf (sender.Equals(lnkDelete)) Then

                For Each currentInstance As DataGridItem In grdInstances.Items

                    If (currentInstance.ItemType.Equals(ListItemType.Item)) Or (currentInstance.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkInstance As CheckBox = currentInstance.FindControl("chkInstance")
                        Dim lblInstanceID As Label = currentInstance.FindControl("lblInstanceID")

                        If (chkInstance.Checked) Then
                            tss_DKP.tss_DeleteInstance(CInt(lblInstanceID.Text))
                        End If

                    End If

                Next

                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkSync)) Then

                Dim strWarning As String = Null.NullString

                For Each currentInstance As DataGridItem In grdInstances.Items

                    If (currentInstance.ItemType.Equals(ListItemType.Item)) Or (currentInstance.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkInstance As CheckBox = currentInstance.FindControl("chkInstance")
                        Dim lblInstanceID As Label = currentInstance.FindControl("lblInstanceID")

                        If (chkInstance.Checked) Then
                            strWarning = strWarning + IIf(strWarning.Length > 0, "<br>", "") + SyncInstance(CInt(lblInstanceID.Text))
                        End If

                    End If

                Next

                ManagePageState(PageState.View)
                lblWarning.Text = strWarning

            ElseIf (sender.Equals(lnkSubmit)) Then

                If (vsPageState = PageState.Add) Then

                    If (txtInstanceName.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Instance name can not be empty."
                    Else

                        Dim objNewInstance As New tss_InstanceInfo : objNewInstance = CBO.InitializeObject(objNewInstance, GetType(tss_InstanceInfo))

                        objNewInstance.InstanceName = txtInstanceName.Text.Trim
                        objNewInstance.InstanceWowHeadID = txtInstanceWowHeadID.Text.Trim
                        objNewInstance.InstanceHeroicFlag = chkInstanceHeroicFlag.Checked
                        objNewInstance.BoardID = CInt(Settings("BoardID"))

                        Try
                            tss_DKP.tss_AddInstance(objNewInstance)
                        Catch ex As ApplicationException
                            lblWarning.Text = "Error: Trying to add instance resulted in the following error (" + ex.Message + ")."
                        End Try

                    End If

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.SingleUpdate) Then

                    For Each currentInstance As DataGridItem In grdInstances.Items

                        If (currentInstance.ItemType.Equals(ListItemType.Item)) Or (currentInstance.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkInstance As CheckBox = currentInstance.FindControl("chkInstance")
                            Dim lblInstanceID As Label = currentInstance.FindControl("lblInstanceID")

                            If (chkInstance.Checked) Then

                                Dim objExistingInstance As tss_InstanceInfo = tss_DKP.tss_GetInstance(CInt(lblInstanceID.Text))

                                If (objExistingInstance Is Nothing) Then
                                    lblWarning.Text = "Error: Trying to update instance resulted in the following error (Instance in selection not found.)."
                                Else

                                    objExistingInstance.InstanceName = txtInstanceName.Text.Trim
                                    objExistingInstance.InstanceWowHeadID = txtInstanceWowHeadID.Text.Trim
                                    objExistingInstance.InstanceHeroicFlag = chkInstanceHeroicFlag.Checked

                                    Try
                                        tss_DKP.tss_UpdateInstance(objExistingInstance)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = "Error: Trying to update instance resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.MultiUpdate) Then

                    For Each currentInstance As DataGridItem In grdInstances.Items

                        If (currentInstance.ItemType.Equals(ListItemType.Item)) Or (currentInstance.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkInstance As CheckBox = currentInstance.FindControl("chkInstance")
                            Dim lblInstanceID As Label = currentInstance.FindControl("lblInstanceID")

                            If (chkInstance.Checked) Then

                                Dim objExistingInstance As tss_InstanceInfo = tss_DKP.tss_GetInstance(CInt(lblInstanceID.Text))

                                If (objExistingInstance Is Nothing) Then
                                    lblWarning.Text = lblWarning.Text + IIf(lblWarning.Text.Length > 0, "<br>", "") _
                                        + "Error: Trying to update instance resulted in the following error (Instance in selection not found.)."
                                Else

                                    objExistingInstance.InstanceHeroicFlag = chkInstanceHeroicFlag.Checked

                                    Try
                                        tss_DKP.tss_UpdateInstance(objExistingInstance)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = lblWarning.Text + "Error: Trying to update instance (" _
                                            + objExistingInstance.InstanceName + ") resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    BindPage()

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                End If

            ElseIf (sender.Equals(lnkCancel)) Then

                ManagePageState(PageState.View)

            End If

        End Sub

#End Region

#Region "Public Methods"

        Public Sub Initialize()

            ManagePageState(PageState.View)

        End Sub

#End Region

    End Class

End Namespace
